package cn.kgc.education.controller;

import cn.hutool.captcha.LineCaptcha;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.IOException;

/**
 * @author 课工场
 * @date 2024/9/6
 * @description  验证码图片请求处理接口   请求该接口可以在前端页面中生成一张验证码图片
 */
@Controller
@RequestMapping("captcha")
public class CaptchaController {

    // 创建一个方法编写具体如何生成一个验证码      request   请求对象  response 响应对象    /captcha/img
    @RequestMapping("img")
    public void  createCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {

        LineCaptcha lineCaptcha = new LineCaptcha(110, 50, 4, 3);
        // 获取验证码
        String code = lineCaptcha.getCode();
        System.out.println("code = " + code);

        //  session 会话对象
        HttpSession session = request.getSession();
        session.setAttribute("code",code);


        // 将验证码图片响应到前端页面
        ServletOutputStream outputStream = response.getOutputStream();     //  响应流  可以将图片写出到浏览器
        lineCaptcha.write(outputStream);

        // 释放资源
        outputStream.close();

    }

}
